const jwt = require('jsonwebtoken')

//token私钥
let tokenPrivateKey = 'k7kls23sad6oir0nv'

/* 生成token */
function generateToken(data) {
	let token = jwt.sign({
		//token到期时间
		exp: Math.floor(Date.now() / 1000) + (60 * 60),
		//需要加密的数据(uid)
		data
	}, tokenPrivateKey)
	return token
}

/* 验证token */
function verifyToken(data) {
	try {
		let decoded = jwt.verify(data, tokenPrivateKey)
		console.log('token验证成功')
		return decoded
	} catch (e) {
		console.log('token异常')
		return false
	}
}

/* 随机昵称 */
function generateName() {
	//随机字符
	let charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	//昵称前缀
	let nameString = '小溜';
	for (var i = 0; i < 5; i++) {
		var randomPoz = Math.floor(Math.random() * charSet.length);
		nameString += charSet.substring(randomPoz, randomPoz + 1);
	}
	return nameString
}

module.exports = {
	generateToken,
	verifyToken,
	generateName
}
